package com.reyco1.medusa.display.container
{
	import com.reyco1.medusa.display.SmartSprite;
	
	import flash.display.DisplayObject;
	
	public class Stack extends SmartSprite
	{
		private var _selectedChild:DisplayObject;
		private var _selectedIndex:int;
		
		private var views:Array;
		
		public function Stack()
		{
			super();
			views = [];
		}
		
		override public function addChild(child:DisplayObject):DisplayObject
		{
			super.addChild(child);
			views.push(child);
			
			if(views.length > 1)
			{
				child.visible = false;
			}
			else
			{
				child.visible = true;
				_selectedChild = child;
				_selectedIndex = 0;
			}
			return child;
		}
		
		override public function removeChild(child:DisplayObject):DisplayObject
		{
			views.splice(getChildIndex(child), 1);
			return super.addChild(child);
		}
		
		override public function removeAllChildren():void
		{
			views = [];
			super.removeAllChildren();
		}
		
		override public function addChildAt(child:DisplayObject, index:int):DisplayObject
		{
			throw new Error("[Stack] : Cannot add child at a specific index.");
		}
		
		override public function removeChildAt(index:int):DisplayObject
		{
			throw new Error("[Stack] : Cannot remove child by index.");
		}
		
		override protected function onRemoved():void
		{
			removeAllChildren();
			removeAllListeners();
		}
		
		/* properties */
		
		public function set selectedChild(child:DisplayObject):void
		{
			_selectedChild.visible = false;
			
			_selectedChild = child;
			_selectedChild.visible = true;
			_selectedIndex = getChildIndex(_selectedChild);
		}

		public function get selectedChild():DisplayObject
		{
			return _selectedChild;
		}

		public function get selectedIndex():int
		{
			return _selectedIndex;
		}

		public function set selectedIndex(value:int):void
		{
			_selectedIndex = value;
			selectedChild = getChildAt(value);
		}

	}
}